<template>
  <div>
    <NavBar :title="detail.name" :leftArrow="true" :clickLeft="goBack" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.address"
        required
        right-icon="location-o"
        label="飞行地址："
        placeholder="请选择飞行地址"
        @click-right-icon="changeAddress"
        :rules="[{ required: true, message: '选择飞行地址' }]"
      />
      <van-field type="digit" :label="typeLabelMap[detail.type]" required>
        <template #input>
          <van-stepper v-model="form.area" integer @input="onarea" />
          <span style="margin-left: 0.2rem">{{
            typeUnitMap[detail.type]
          }}</span>
        </template>
      </van-field>
      <van-field
        v-model="date"
        readonly
        required
        label="持续日期："
        placeholder="请选择持续日期"
        @click-input="show = true"
        :rules="[
          { required: true, message: '请选择持续日期', trigger: 'onChange' },
        ]"
      />
      <!-- <van-field name="radio" label="紧急程度：">
                <template #input>
                    <van-radio-group v-model="form.isUrgent" direction="horizontal">
                    <van-radio :name="0">不紧急</van-radio>
                    <van-radio :name="1" checked-color="red">
                        <template #default>
                            <span style="color:red">紧急（加收20%加急费用）</span>
                        </template>
                    </van-radio>
                    </van-radio-group>
                </template>
            </van-field> -->
      <van-field
        v-model="form.remark"
        rows="1"
        autosize
        maxlength="70"
        label="信息备注："
        placeholder="请输入备注信息"
        type="textarea"
      />
      <van-field name="uploader" label="图片">
        <template #input>
          <van-uploader
            v-model="fileList"
            upload-icon="plus"
            :after-read="afterRead"
            @delete="handleDelImg"
          >
          </van-uploader>
        </template>
      </van-field>
      <van-field readonly label="预计积分：">
        <template #input>
          <!-- <span><span style="color: red">{{form.total}}</span>（{{detail.price}}积分/{{detail.typeName}}）</span> -->
          <span v-if="detail.type == 1"
            ><span style="color: red">{{ form.total }}</span
            >（{{ form.area }}点数*{{ detail.price }}积分/8h）</span
          >
          <span v-if="detail.type == 2"
            ><span style="color: red">{{ form.total }}</span
            >（{{ form.area }}公里*{{ detail.price }}积分/公里）</span
          >
          <span v-if="detail.type == 3"
            ><span style="color: red">{{ form.total }}</span
            >（{{ form.area }}平方公里*{{ detail.price }}积分/平方公里）</span
          >
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >下单</van-button
        >
      </div>
    </van-form>
    <van-calendar
      v-model="show"
      color="#48A1FA"
      type="range"
      :default-date="[
        new Date(new Date().setDate(new Date().getDate() + 1)),
        new Date(new Date().setDate(new Date().getDate() + 1)),
      ]"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
import NavBar from "@/components/NavBar";
import moment from "moment";
import { CreateTask } from "@/api/task";
import { UploadOss } from "@/api/common";
import { GetInspectionView } from "@/api/home";
import { Toast } from "vant";
import { mapActions, mapGetters } from "vuex";
export default {
  components: {
    NavBar,
  },
  data: () => ({
    count: 1,
    days: 1,
    row: null,
    id: "",
    title: "",
    form: {
      address: undefined,
      endTime: moment().add(1, "days").format("YYYY-MM-DD"),
      geom: [],
      images: [],
      inspectionId: undefined,
      // isUrgent: undefined,
      remark: undefined,
      startTime: moment().add(1, "days").format("YYYY-MM-DD"),
      area: 1,
      total: undefined,
    },
    fileList: [],
    date:
      moment().add(1, "days").format("YYYY-MM-DD") +
      " ~ " +
      moment().add(1, "days").format("YYYY-MM-DD"),
    show: false,
    detail: {},
    typeLabelMap: {
      1: "预计点数：",
      2: "预计长度：",
      3: "预计面积：",
    },
    typeUnitMap: {
      1: "个",
      2: "公里",
      3: "平方公里",
    },
  }),
  watch: {
    "form.area": {
      handler() {
        let { area } = this.form,
          { price } = this.detail;
        this.form.total = area * price;
      },
      deep:true
    },
  },
  computed: {
    // ...mapGetters({'form': 'form'})
    // form(){
    //     console.log(this.$store.getters.form)
    //     return this.$store.getters.form
    // }
  },
  methods: {
    onarea() {
     let timer = null;
     clearTimeout(timer)
    timer =  setTimeout(()=>{
          if (this.form.area <= 0) {
        Toast({
          message: "输入的数值必须大于0",
          position: "top",
        });
      }
     },500)
    },
    ...mapActions("order", ["setAdd"]),
    goBack() {
      this.setAdd({});
      let { pid } = this.$route.params;
      this.$router.replace(`/industry/${pid}`);
    },
    async GetInspectionView() {
      let { data } = await GetInspectionView(this.id);
      this.detail = data;
      this.title = data.name;
      let { area } = this.form,
        { price } = this.detail;
      this.form.total = area * price;
    },
    changeAddress() {
      this.setAdd(this.form);
      this.$router.push(`/map?id=${this.id}`);
    },
    async onSubmit() {
      let { status, message } = await CreateTask({
        ...this.form,
        inspectionId: this.id,
        images: JSON.stringify(this.form.images),
        geom: JSON.stringify(this.form.geom),
      });
      if (status === 1) {
        Toast.success("下单成功");
        this.setAdd({});
        this.$router.push(`/order`);
      } else {
        Toast.fail(message);
      }
    },
    formatDate(date) {
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },
    onConfirm(date) {
      const [start, end] = date;
      this.show = false;
      this.form.startTime = moment(start).format("YYYY-MM-DD");
      this.form.endTime = moment(end).format("YYYY-MM-DD");

      this.date = `${moment(start).format("YYYY-MM-DD")} ~ ${moment(end).format(
        "YYYY-MM-DD"
      )}`;
    },
    async afterRead(data) {
      console.log(data);
      let { file } = data;
      let formData = new FormData();
      formData.append("uploadFile", file);
      let {
        data: { filePath },
      } = await UploadOss(formData);
      // this.form.images.push(filePath)
      let size = file.size / 1024 / 1024;
      this.form.images.push({
        filePath,
        name: file.name,
        size: size < 0.1 ? 0.1 : size.toFixed(1),
      });
      if (!this.addmsg.content) {
        this.addmsg.content = file.name;
      }
    },
    handleDelImg(data, obj) {
      let { index } = obj;
      this.form.images.splice(index, 1);
    },
  },
  mounted() {
    this.id = this.$route.params.id;
    this.GetInspectionView();
    // let { address } = this.$route.query
    let { addForm } = this.$store.getters,
      { form } = this;
    console.log("store数据----》", this.$store.getters.addForm);

    Object.keys(form).forEach((k) => {
      if (addForm[k]) {
        form[k] = addForm[k];
      }
    });

    this.date = form.startTime + " ~ " + form.endTime;
    this.form = form;
    this.fileList = addForm.images
      ? addForm.images.map((item) => {
          return {
            url: item,
          };
        })
      : [];

    // if(address){
    //     console.log("地图选点结果", JSON.parse(address))
    //     let position_arr = JSON.parse(address)
    //     this.form.address = position_arr[position_arr.length - 1].address
    //     this.form.geom = position_arr.map(item => item.lnglat)
    //     console.log(this.form)
    // }

    // console.log(new Date(new Date().setDate(new Date().getDate() + 1)))
  },
};
</script>

<style lang="scss" scoped>
// @media screen and (max-width: 600px) {
//     .back{
//         width: 24px;height: 24px;
//         color: white;
//         position: absolute;
//         text-align: center;
//         line-height: 24px;
//         top: 12px;left: 8px;
//         span{
//             font-size: 16px;
//         }
//     }
//     .banner {
//         width: 100%;
//         height: 40px;
//         background: #48A1FA;
//         color: white;
//         text-align: center;
//         padding-top: 20px;
//         font-size: 12px;
//         letter-spacing: 1px;
//     }
//     ul{
//         li{
//             margin-bottom: 16px;
//         }
//         li:nth-of-type(2){
//             div{
//                 width: 80px;
//                 background: #E5EFF6;
//                 display: flex;
//                 justify-content: space-between;
//                 span{
//                     display: block;
//                     width: 30%;height: 100%;
//                     text-align: center;
//                     border: 1px #48A1FA solid;
//                     font-size: 18px;
//                 }
//                 span:nth-of-type(2){
//                     border: none;
//                     font-size: 8px;
//                 }
//             }
//         }
//         li:nth-of-type(3){
//             div{
//                 background: #E5EFF6;
//                 width: 90px;height: 20px;
//                 line-height: 20px;
//                 font-size: 8px;
//                 padding: 0px 4px;
//                 >span{
//                     font-size: 8px;
//                 }
//             }
//         }
//         li:nth-of-type(4){
//             div{
//                 width: 14px;height: 14px;
//                 border-radius: 50%;
//                 border: 1px #BDBDBD solid;
//                 margin-top: 2px;
//                 margin-right: 4px;
//                 text-align: center;
//                 line-height: 14px;
//                 color: white;
//                 background: #48A1FA;
//                 span{
//                     font-size: 8px;
//                 }
//             }
//             .last{
//                 background: white;
//             }
//         }
//         li:nth-of-type(7){
//             border-bottom: 1px #E0E0E0 solid;
//         }
//         li:nth-of-type(8){
//             border-bottom: 1px #E0E0E0 solid;
//             height: 40px;
//         }
//         input{
//             background: #E5EFF6;
//             font-size: 8px;
//             width: 65%;
//             height: 22px;
//             padding: 5px 12px;
//             letter-spacing: 1px;
//             outline: none;
//         }
//     }
//     .btn{
//         width: 80px;height: 30px;
//         line-height: 30px;margin: auto;
//         background: #48A1FA;
//         text-align: center;
//         color: white;
//         border-radius: 8px;
//         font-size: 8px;
//     }
// }

// @media screen and (min-width:640px) and (max-width: 960px) {
//     .back{
//         width: 28px;height: 28px;
//         color: white;
//         position: absolute;
//         text-align: center;
//         line-height: 28px;
//         font-size: 24px;
//         top: 18px;left: 14px;
//         span{
//             font-size: 22px;
//         }
//     }
//     .banner{
//         width: 100%;
//         height: 60px;
//         background: #48A1FA;
//         color: white;
//         text-align: center;
//         padding-top: 30px;
//         font-size: 18px;
//         letter-spacing: 2px;
//     }
//     ul{
//         li{
//             margin-bottom: 20px;
//         }
//         li:nth-of-type(2){
//             div{
//                 width: 100px;
//                 background: #E5EFF6;
//                 display: flex;
//                 justify-content: space-between;
//                 span{
//                     display: block;
//                     width: 30%;height: 100%;
//                     text-align: center;
//                     border: 1px #48A1FA solid;
//                     font-size: 20px;
//                 }
//                 span:nth-of-type(2){
//                     border: none;
//                     font-size: 16px;
//                 }
//             }
//         }
//         li:nth-of-type(3){
//             div{
//                 background: #E5EFF6;
//                 width: 110px;height: 30px;
//                 font-size: 14px;
//                 padding: 2px 6px;
//                 span{
//                     line-height: 24px;
//                 }
//             }
//         }
//         li:nth-of-type(4){
//             div{
//                 width: 18px;height: 18px;
//                 border-radius: 50%;
//                 border: 1px #BDBDBD solid;
//                 margin-top: 4px;
//                 margin-right: 4px;
//                 text-align: center;
//                 line-height: 18px;
//                 color: white;
//                 background: #48A1FA;
//             }
//             .last{
//                 background: white;
//             }
//         }
//         li:nth-of-type(7){
//             border-bottom: 1px #E0E0E0 solid;
//         }
//         li:nth-of-type(8){
//             border-bottom: 1px #E0E0E0 solid;
//             height: 50px;
//         }
//         input{
//             background: #E5EFF6;
//             font-size: 14px;
//             width: 82%;
//             height: 30px;
//             padding: 5px 12px;
//             letter-spacing: 2px;
//             outline: none;
//         }
//     }
//     .btn{
//         width: 150px;height: 40px;
//         line-height: 40px;margin: auto;
//         background: #48A1FA;
//         text-align: center;
//         color: white;
//         border-radius: 10px;
//     }
// }
</style>